package org.feichao.xdao;

import org.feichao.xdao.util.JDBCUtil;
import org.feichao.xdao.util.Log;
import org.feichao.xdao.util.ObjectUtil;

import java.sql.ResultSet;

/**
 * 简单的DAO工具
 *
 * @author zhangzc@djcars.cn
 * @create 2016/11/4
 */
public class Dao<T> {

    Class<T> tClass;

    public Dao(Class<T> _tClass){
        this.tClass = _tClass;
    }

    /**
     * 通过ID获取对象
     *
     * @param id
     * @return
     */
    public T fetchById(Object id){
        String idName = ObjectUtil.extractDbId(tClass);
        String tableName = ObjectUtil.extractDbTable(tClass);
        String dataSourceName = ObjectUtil.extractDataSource(tClass);
        ResultSet rs = null;
        try{
            rs = new JDBCUtil(dataSourceName).executeQuery("select * from "+tableName+" where "+idName+"=?", new Object[]{id});
            if(rs.next()){
                return (T) JDBCUtil.parseResultSet(rs, tClass);
            }
        }catch (Exception e){
            Log.error(e, "Error in Dao.fetchById()");
        }finally {
            JDBCUtil.closeAll(rs);
        }

        return null;
    }

    /**
     * 通过ID删除对象
     *
     * @param id
     * @return
     */
    public boolean deleteById(Object id){
        String idName = ObjectUtil.extractDbId(tClass);
        String tableName = ObjectUtil.extractDbTable(tClass);
        String dataSourceName = ObjectUtil.extractDataSource(tClass);
        try{
            int count = new JDBCUtil(dataSourceName).executeUpdate("delete from "+tableName+" where "+idName+"=?", new Object[]{id});
            return count > 0;
        }catch (Exception e){
            Log.error(e, "Error in Dao.deleteById()");
            return false;
        }
    }
}
